import {saveWebVisit} from '../../bomb/db.visit.js'

// 信息准确完整(但不支持https)
// const url = "http://ip-api.com/json/?lang=zh-CN"
const ipApiUrl = 'https://www.bzchao.com/api/ip-api/json'

$(document).ready(() => {
    getIpLocationBySoHu(sohuRes => {
        if (sohuRes.error) {
            saveWebVisit(sohuRes)
            return
        }
        getIpLocationByIpApi(sohuRes.ip, res => {
            saveWebVisit(res)
        })
    })
});

/**
 * 获取ip地址信息
 * @param callback 获取成功后回调方法
 */
function getIpLocationByIpApi(ip, callback) {
    $.ajax({
        url: `${ipApiUrl}/${ip}?lang=zh-CN`,
        success: function (res) {
            console.log(res);
            if (res.status === 'success') {
                callback({
                    address: res.country + "," + res.regionName + "," + res.city,
                    city: res.city,
                    ip: ip,
                })
            } else {
                callback({
                    error: JSON.stringify(res),
                    ip: ip,
                })
            }
        },
        // Ajax接口出现错误时执行下述代码
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            /*弹出jqXHR对象的信息*/
            console.error(XMLHttpRequest, textStatus, errorThrown);
            callback({
                error: textStatus,
                address: "",
                city: "",
                ip: "",
            })
        }
    })
}

//只有ip信息，城市信息不正确
const soHuUrl = "//pv.sohu.com/cityjson?ie=utf-8"

/**
 * 获取ip地址信息
 * @param callback 获取成功后回调方法
 */
function getIpLocationBySoHu(callback) {
    $.getScript(soHuUrl)
        .done(function (script, textStatus, jqxhr) {
            callback({
                address: "",
                city: returnCitySN.cname,
                ip: returnCitySN.cip,
            })
        })
        .fail(function () {
            callback({
                error: "加载SoHuIP地址失败",
                address: "",
                city: "",
                ip: "",
            })
        });
}

